﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Win.CSkin.Test
{
    public partial class FrmDGVTest1 : Form
    {
        public FrmDGVTest1()
        {
            InitializeComponent();
        }

        private void FrmDGVTest1_Load(object sender, EventArgs e)
        {
            List<TestUserInfo> list = new List<TestUserInfo>();
            for (int i = 0; i < 10; i++) //插入10条数据。
            {
                TestUserInfo user = new TestUserInfo
                {
                    UserId = "UserId" + i,
                    UserName = "UserName" + i,
                    UserEnabled = i % 2 == 0
                };
                list.Add(user);
            }

            dgvEx.AutoGenerateColumns = false;
            dgvEx.DataSource = list;

            BindSourceGrid();
        }


        void BindSourceGrid()
        {
            List<TestUserInfo> list = new List<TestUserInfo>();
            for (int i = 0; i < 10; i++) //插入10条数据。
            {
                TestUserInfo user = new TestUserInfo
                {
                    UserId = "UserId" + i,
                    UserName = "UserName" + i,
                    UserEnabled = i % 2 == 0
                };
                list.Add(user);
            }

            dataGrid1.BorderStyle = BorderStyle.FixedSingle;
            dataGrid1.FixedColumns = 2;
            dataGrid1.FixedRows = 1;
            dataGrid1.Rows.HeaderHeight = 35;
            dataGrid1.Rows.RowHeight = 30;

            //Borders
            DevAge.Drawing.RectangleBorder border = new DevAge.Drawing.RectangleBorder(new DevAge.Drawing.BorderLine(Color.ForestGreen), new DevAge.Drawing.BorderLine(Color.ForestGreen));

            //Standard Views Link列居中样式
            SourceGrid.Cells.Views.Link viewLink = new SourceGrid.Cells.Views.Link();
            //viewLink.BackColor = Color.DarkSeaGreen;
            viewLink.Border = border;
            viewLink.ImageAlignment = DevAge.Drawing.ContentAlignment.MiddleCenter;
            viewLink.TextAlignment = DevAge.Drawing.ContentAlignment.MiddleCenter;

            //标题行样式
            DevAge.Drawing.VisualElements.ColumnHeader flatHeader = new DevAge.Drawing.VisualElements.ColumnHeader();
            flatHeader.Border = border;
            flatHeader.BackColor = Color.White;
            flatHeader.BackgroundColorStyle = DevAge.Drawing.BackgroundColorStyle.Linear;
            SourceGrid.Cells.Views.ColumnHeader headerView = new SourceGrid.Cells.Views.ColumnHeader();
            headerView.Font = new Font(dataGrid1.Font, FontStyle.Bold | FontStyle.Underline);
            headerView.Background = flatHeader;
            headerView.ForeColor = Color.Black;
            headerView.TextAlignment = DevAge.Drawing.ContentAlignment.MiddleCenter;

            //Create the views 
            //选中后加粗样式
            SourceGrid.Cells.Views.Cell viewSelected = new SourceGrid.Cells.Views.Cell();
            viewSelected.Font = new Font(dataGrid1.Font, FontStyle.Bold);
            viewSelected.ForeColor = Color.DarkGreen;

            //Create selected conditions
            SourceGrid.Conditions.ConditionView selectedConditionBold = new SourceGrid.Conditions.ConditionView(viewSelected);
            //复选框为选中状态才改变样式
            selectedConditionBold.EvaluateFunction = delegate (SourceGrid.DataGridColumn column, int gridRow, object itemRow)
            {
                TestUserInfo row = (TestUserInfo)itemRow;
                return row != null && row.UserEnabled == true; //满足条件
                //return true;
            };

            SourceGrid.Cells.Controllers.CustomEvents clickEvent = new SourceGrid.Cells.Controllers.CustomEvents();
            clickEvent.Click += new EventHandler(clickEvent_Click);

            //Create columns
            //删除按钮列--图片
            SourceGrid.DataGridColumn gridColumn;
            gridColumn = dataGrid1.Columns.Add(null, "删除", new SourceGrid.Cells.Link());
            gridColumn.Width = 50;
            gridColumn.DataCell.AddController(clickEvent);
            gridColumn.DataCell.View = viewLink;
            gridColumn.HeaderCell.View = headerView;
            ((SourceGrid.Cells.Link)gridColumn.DataCell).Image = Properties.Resources.skinToolStrip1_BaseItemDown;

            //编辑列--Link
            gridColumn = dataGrid1.Columns.Add(null, "编辑", new SourceGrid.Cells.Link("编辑"));
            gridColumn.Width = 50;
            gridColumn.DataCell.AddController(new CellClickEvent());
            gridColumn.DataCell.View = viewLink;
            gridColumn.HeaderCell.View = headerView;

            //详情列--按钮
            gridColumn = dataGrid1.Columns.Add(null, "详情", new SourceGrid.Cells.Button("详情"));
            gridColumn.Width = 50;
            gridColumn.DataCell.AddController(new CellClickEvent());
            gridColumn.DataCell.View.TextAlignment = DevAge.Drawing.ContentAlignment.MiddleCenter;
            gridColumn.HeaderCell.View = headerView;

            gridColumn = dataGrid1.Columns.Add("UserId", "用户ID", typeof(string));
            gridColumn.Width = 100;
            gridColumn.HeaderCell.View = headerView;
            gridColumn.Conditions.Add(selectedConditionBold);

            SourceGrid.Cells.Controllers.ToolTipText toolTipController =
                new SourceGrid.Cells.Controllers.ToolTipText();
            toolTipController.IsBalloon = true;

            //gridColumn = dataGrid1.Columns.Add("UserName", "用户名", new SourceGrid.Cells.Cell { ToolTipText = "Sample Tooltip" });
            gridColumn = dataGrid1.Columns.Add("UserName", "用户名", typeof(string));
            gridColumn.Width = 200;
            gridColumn.HeaderCell.View = headerView;
            gridColumn.DataCell.AddController(toolTipController);  //单列加ToolTip
            gridColumn.DataCell.Model.AddModel(MyToolTipModel.Default);
            gridColumn.Conditions.Add(selectedConditionBold);

            gridColumn = dataGrid1.Columns.Add("UserEnabled", "状态", typeof(bool));
            gridColumn.Width = 50;
            gridColumn.HeaderCell.View = headerView;

            ////所有列添加ToolTipText
            //foreach (SourceGrid.DataGridColumn col in dataGrid1.Columns)
            //{
            //    col.DataCell.AddController(SourceGrid.Cells.Controllers.ToolTipText.Default);
            //    col.DataCell.Model.AddModel(MyToolTipModel.Default);
            //}

            var mList = new DevAge.ComponentModel.BoundList<TestUserInfo>(list);
            mList.AllowDelete = false;
            mList.AllowNew = false;
            mList.AllowEdit = false;
            dataGrid1.DataSource = mList;
        }

        private class CellClickEvent : SourceGrid.Cells.Controllers.ControllerBase
        {
            public override void OnClick(SourceGrid.CellContext sender, EventArgs e)
            {
                base.OnClick(sender, e);

                MessageBox.Show(sender.Position.ToString());

                SourceGrid.DataGrid grid = (SourceGrid.DataGrid)sender.Grid;
                var selected = grid.SelectedDataRows;
                TestUserInfo info = selected[0] as TestUserInfo;
                MessageBox.Show(info.UserName);
                //grid.DeleteSelectedRows();
            }
        }

        private class MyToolTipModel : SourceGrid.Cells.Models.IToolTipText
        {
            public static readonly MyToolTipModel Default = new MyToolTipModel();

            public string GetToolTipText(SourceGrid.CellContext cellContext)
            {
                SourceGrid.DataGrid grid = (SourceGrid.DataGrid)cellContext.Grid;
                TestUserInfo row = (TestUserInfo)grid.Rows.IndexToDataSourceRow(cellContext.Position.Row);
                if (row != null)
                {
                    if (cellContext.Position.Column == 4) return row.UserName;
                    else return string.Empty;
                }
                else
                    return string.Empty;
            }
        }


        private void clickEvent_Click(object sender, EventArgs e)
        {
            SourceGrid.CellContext context = (SourceGrid.CellContext)sender;
            MessageBox.Show(this, context.Position.ToString());
        }

        private void btnCsv_Click(object sender, EventArgs e)
        {
            try
            {
                SaveFileDialog sfd = new SaveFileDialog();
                string tradeTime = DateTime.Now.ToString("yyyyMMddHHmmss");
                sfd.FileName = "计算报表" + tradeTime;
                if (sfd.ShowDialog() != DialogResult.OK) return;
                //保存
                var exportFileName = System.IO.Path.Combine(sfd.FileName.Substring(0, sfd.FileName.Length - 18), sfd.FileName.Substring(sfd.FileName.Length - 18) + ".csv");

                using (var writer = new System.IO.StreamWriter(exportFileName, false, System.Text.Encoding.Default))
                {
                    SourceGrid.Exporter.CSV csv = new SourceGrid.Exporter.CSV();
                    csv.Export(dataGrid1, writer);
                    writer.Close();
                    MessageBox.Show("导出成功!");
                }

                DevAge.Shell.Utilities.OpenFile(exportFileName);
            }
            catch (Exception ex)
            {
                MessageBox.Show("导出失败!" + ex.Message);
            }
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            PrintPreviewDialog dlg = new PrintPreviewDialog();
            SourceGrid.Exporter.GridPrintDocument pd = new SourceGrid.Exporter.GridPrintDocument(this.dataGrid1);
            pd.RangeToPrint = new SourceGrid.Range(0, 3, this.dataGrid1.Rows.Count - 1, this.dataGrid1.Columns.Count - 1);
            pd.PageHeaderText = "Print sample\t\tSourceGrid print document sample";
            pd.PageTitleText = "\tSample grid";
            pd.PageFooterText = "\tPage [PageNo] from [PageCount]";
            dlg.Document = pd;
            dlg.ShowDialog(this);
        }
    }
}
